import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/vehicle_type_mixin.dart';
import 'package:inmotion_pro/pages/models/auth_application_model.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

enum BindApplyType { fromMe, toMe }

// 车辆授权申请列表项 - 优化版本
class BindApplyItem extends StatelessWidget with VehicleTypeMixin {
  /// 申请类型
  final BindApplyType? applyType;
  final AuthApplicationModel? bindApplyModel;
  final void Function()? onTap;
  final void Function()? onAccept;
  final void Function()? onReject;

  const BindApplyItem({
    Key? key,
    required this.applyType,
    required this.bindApplyModel,
    this.onTap,
    this.onAccept,
    this.onReject,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isFromMe = applyType == BindApplyType.fromMe;

    // 获取相关用户信息
    final targetUser =
        isFromMe ? bindApplyModel?.toUser : bindApplyModel?.fromUser;

    return Material(
      borderRadius: BorderRadius.circular(20),
      color: theme.cardColor,
      elevation: 3,
      shadowColor: colorScheme.shadow.withOpacity(0.15),
      child: InkWell(
        onTap: isFromMe ? onTap : null, // 只有fromMe才可点击整个卡片
        borderRadius: BorderRadius.circular(20),
        child: Container(
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            border: Border.all(
              color: colorScheme.error.withOpacity(0.2),
              width: 1.5,
            ),
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                theme.cardColor,
                theme.cardColor.withOpacity(0.95),
              ],
            ),
          ),
          child: Column(
            children: [
              // 顶部：用户信息和申请方向
              _buildTopSection(context, isFromMe, targetUser),
              const SizedBox(height: 16),

              // 中部：车辆信息
              _buildMiddleSection(context),
              const SizedBox(height: 12),

              // 底部：状态和操作
              _buildBottomSection(context, isFromMe),
            ],
          ),
        ),
      ),
    );
  }

  // 顶部：用户信息和申请方向
  Widget _buildTopSection(
    BuildContext context,
    bool isFromMe,
    BindApplyUser? targetUser,
  ) {
    return isFromMe
        ? Row(
            children: [
              // 申请信息
              Expanded(
                  child: Padding(
                padding: EdgeInsets.only(left: CONTENT_MARGIN),
                child: Text(
                  isFromMe
                      ? local.vehicle_authorization_apply_to(
                          targetUser?.nickName ?? '未知用户')
                      : local.vehicle_authorization_apply_from(
                          targetUser?.nickName ?? '未知用户'),
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Theme.of(context)
                            .colorScheme
                            .onSurface
                            .withOpacity(0.7),
                      ),
                ),
              )),
              const SizedBox(width: 12),
              // 用户头像
              _buildUserAvatar(
                context,
                targetUser?.avatar,
                targetUser?.nickName,
              ),
            ],
          )
        : Row(
            children: [
              // 用户头像
              _buildUserAvatar(
                context,
                targetUser?.avatar,
                targetUser?.nickName,
              ),
              const SizedBox(width: 12),

              // 申请信息
              Expanded(
                child: Text(
                  isFromMe
                      ? local.vehicle_authorization_apply_to(
                          targetUser?.nickName ?? '未知用户')
                      : local.vehicle_authorization_apply_from(
                          targetUser?.nickName ?? '未知用户'),
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Theme.of(context)
                            .colorScheme
                            .onSurface
                            .withOpacity(0.7),
                      ),
                ),
              ),
            ],
          );
  }

  // 用户头像组件
  Widget _buildUserAvatar(
    BuildContext context,
    String? avatarUrl,
    String? nickname,
  ) {
    return Column(
      children: [
        Container(
          width: 50.w,
          height: 50.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(
              color: Theme.of(context).colorScheme.outline.withOpacity(0.3),
              width: 2,
            ),
          ),
          child: ClipOval(
            child: avatarUrl != null && avatarUrl.isNotEmpty
                ? Image.network(
                    avatarUrl,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return _buildPlaceholderAvatar(context, nickname);
                    },
                  )
                : _buildPlaceholderAvatar(context, nickname),
          ),
        ),
      ],
    );
  }

  // 默认头像
  Widget _buildPlaceholderAvatar(BuildContext context, String? nickname) {
    return Container(
      color: Theme.of(context).colorScheme.primary.withOpacity(0.1),
      child: Center(
        child: Icon(
          Icons.person_rounded,
          size: 24,
          color: Theme.of(context).colorScheme.primary.withOpacity(0.5),
        ),
      ),
    );
  }

  // 中部：车辆信息
  Widget _buildMiddleSection(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.2),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: Theme.of(context).colorScheme.outline.withOpacity(0.1),
        ),
      ),
      child: Row(
        children: [
          // 车辆图片
          _buildVehicleImage(context),
          const SizedBox(width: 12),

          // 车辆信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  bindApplyModel?.bleName ?? '未知车型',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.w600,
                        color: Theme.of(context).colorScheme.onSurface,
                      ),
                ),
                SizedBox(height: 3.w),
                Row(
                  children: [
                    Icon(
                      Icons.qr_code_rounded,
                      size: 14,
                      color: Theme.of(context)
                          .colorScheme
                          .primary
                          .withOpacity(0.6),
                    ),
                    SizedBox(width: 4.w),
                    Text(
                      bindApplyModel?.sn ?? 'N/A',
                      style: Theme.of(context).textTheme.labelSmall?.copyWith(
                            color: Theme.of(context)
                                .colorScheme
                                .onSurface
                                .withOpacity(0.6),
                          ),
                    ),
                  ],
                ),
                SizedBox(height: 3.w),
                Row(
                  children: [
                    Icon(
                      Icons.access_time_rounded,
                      size: 14,
                      color: Theme.of(context)
                          .colorScheme
                          .primary
                          .withOpacity(0.6),
                    ),
                    const SizedBox(width: 4),
                    Text(
                      _formatTime(bindApplyModel?.createdAt ?? 0),
                      style: Theme.of(context).textTheme.labelSmall?.copyWith(
                            color: Theme.of(context)
                                .colorScheme
                                .onSurface
                                .withOpacity(0.6),
                          ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 车辆图片
  Widget _buildVehicleImage(BuildContext context) {
    return Container(
      width: 60.w,
      height: 60.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        color: Theme.of(context).colorScheme.primary.withOpacity(0.05),
        border: Border.all(
          color: Theme.of(context).colorScheme.outline.withOpacity(0.1),
        ),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: _getVehicleImage(context),
      ),
    );
  }

  // 获取车辆图片
  Widget _getVehicleImage(BuildContext context) {
    return Container(
      color: Theme.of(context).colorScheme.primary.withOpacity(0.1),
      child: Center(
        child: bindApplyModel?.bleName == null
            ? Icon(
                Icons.electric_scooter_rounded,
                size: 32,
                color: Theme.of(context).colorScheme.primary.withOpacity(0.5),
              )
            : Padding(
                padding: EdgeInsets.all(6.w),
                child: Image.asset(vehicleTypeMixinGetVehicleType(
                        bleName: bindApplyModel?.bleName ?? '')
                    .assetPath),
              ),
      ),
    );
  }

  // 底部：状态和操作
  Widget _buildBottomSection(BuildContext context, bool isFromMe) {
    if (isFromMe || bindApplyModel?.state != AuthApplicationState.pending) {
      // 我发起的申请：显示状态
      return Row(
        children: [
          // 状态标签
          _buildStatusChip(context),
          const Spacer(),
        ],
      );
    } else {
      // 待处理状态：显示操作按钮
      return Row(
        children: [
          const Spacer(),
          // 拒绝按钮
          _buildActionButton(
            context,
            local.reject,
            Icons.close_rounded,
            Theme.of(context).colorScheme.error,
            onReject,
          ),
          const SizedBox(width: 12),
          // 同意按钮
          _buildActionButton(
            context,
            local.approve,
            Icons.check_rounded,
            Theme.of(context).colorScheme.primary,
            onAccept,
          ),
        ],
      );
    }
  }

  // 状态标签
  Widget _buildStatusChip(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: GrayColor.gray2,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(
          color: Colors.transparent,
        ),
      ),
      child: Text(
        bindApplyModel?.state?.name ?? '未知状态',
        style: Theme.of(context).textTheme.labelMedium?.copyWith(
              fontWeight: FontWeight.w600,
              color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
            ),
      ),
    );
  }

  // 操作按钮
  Widget _buildActionButton(
    BuildContext context,
    String text,
    IconData icon,
    Color color,
    void Function()? onPressed,
  ) {
    return InkWell(
      onTap: onPressed,
      borderRadius: BorderRadius.circular(16),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: color.withOpacity(0.3),
          ),
        ),
        child: Row(
          children: [
            Icon(
              icon,
              size: 14,
              color: color,
            ),
            const SizedBox(width: 6),
            Text(
              text,
              style: Theme.of(context).textTheme.labelMedium?.copyWith(
                    color: color,
                    fontWeight: FontWeight.w600,
                  ),
            ),
          ],
        ),
      ),
    );
  }

  // 格式化时间
  String _formatTime(int timestamp) {
    final date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
    return '${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
  }
}
